<template>
    <div class="wrap-container">
        <div class="container">
            <div class="header-bar">
                <div class="f-button" @click="onAdd">新建</div>
                <div class="f-button" @click="onUpload">导入</div>
                <div class="f-button" @click="onExport">导出</div>
                <div class="f-button" @click="onSync" v-has="'syncAllData'">一键同步</div>

                <div class="f-input">
                    <el-input
                        placeholder="请输入车牌号码"
                        v-model="queryData.plateCode"
                        class="input-with-select"
                        @keyup.enter.native="onLoadList"
                    >
                        <el-button slot="append" @click="onLoadList">
                            <img src="@/assets/icon/pageIcons/search.png" />
                        </el-button>
                    </el-input>
                </div>
            </div>
            <Table :config="config" ref="table"></Table>
            <el-dialog
                :title="addNew ? '新建' : '编辑'"
                :visible.sync="showDialog"
                width="696px"
                height="40%"
                :close-on-click-modal="false"
            >
                <div class="dialog-note dialog-note-form">
                    <div class="form">
                        <Form
                            class="container-from"
                            :config="config"
                            ref="form"
                            :showDialog="showDialog"
                        >
                        </Form>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <div class="q-button right" @click="onCancel">取消</div>

                    <el-button
                        class="f-button right"
                        @click="handleSubmit"
                        :loading="submitLoading"
                    >
                        确 定
                    </el-button>
                </span>
            </el-dialog>
            <el-dialog
                title="上传"
                :visible.sync="showDialogUpload"
                width="696px"
                height="40%"
                :close-on-click-modal="false"
            >
                <div class="dialog-note dialog-note-form">
                    <div class="form">
                        <div class="container-from">
                            <el-upload
                                class="upload-demo"
                                :action="windowURL + '/limit/yellow/upload'"
                                :headers="uploadToken"
                                :limit="1"
                                :file-list="fileList"
                                :on-success="onUploadSuccess"
                                :before-upload="onBeforeUpload"
                                :on-error="onUploadError"
                                :show-file-list="false"
                            >
                                <el-button size="small" type="primary"
                                    >点击上传</el-button
                                >
                                <div slot="tip" class="el-upload__tip">
                                    只能上传xls/xlsx文件，且不超过10M
                                </div>
                            </el-upload>
                            <el-progress
                                v-if="progressFlag"
                                :percentage="progressUpload"
                            ></el-progress>
                        </div>
                    </div>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import API from "@/api/api_event";
import { formColumns, statusList, tableHeaders } from "./conf";
import { formatDate } from "@/utils/filter";
export default {
    data() {
        return {
            addNew: true,
            updateAddForm: {},
            showDialog: false,
            dataSlot: "",
            startTime: "",
            config: {
                columns: formColumns
                    .concat(this.getFormStartDates())
                    .concat(this.getFormEndDates()),
                formData: {},
                formDataSlot: {},
                headers: tableHeaders.concat(this.getActions()),
                //通过接口获取列表数据 - pageInfo分页的参数
                loadData: (pageInfo) => this.getGrid(pageInfo),
                hasCheckbox: false,
                selectable: this.selectable,
                reserveSelection: false,
                rowKey: (row) => row.id,
            },
            queryData: { plateCode: "" },
            submitLoading: false,
            loading: false,
            showDialogUpload: false,
            windowURL: window.g.event_url,
            uploadToken: {},
            fileList: [],
            progressUpload: 0,
            progressFlag: false,
            timer: Object,
        };
    },
    mounted() {
        this.uploadToken = { token: this.getCookie("applyToken") };
        this.getAreaNameList();
    },

    methods: {
        onLoadList() {
            this.$refs.table.reload();
        },
        getAreaNameList(data) {
            API.eventSelectListBlackAreaName()
                .then((res) => {
                    this.config.columns[0].list = res.data;
                })
                .catch((error) => {});
        },
        getGrid(pageInfo) {
            return new Promise((resolve, reject) => {
                API.eventListYellow({ ...this.queryData, ...pageInfo })
                    .then((res) => {
                        resolve({ data: res.data.list, total: res.data.total });
                    })
                    .catch((error) => {
                        reject();
                    });
            });
        },
        getActions() {
            return {
                prop: "action",
                label: "操作",
                type: "Action",
                value: [
                    {
                        label: "编辑",
                        click: (data) => {
                            this.config.formData = JSON.parse(
                                JSON.stringify(data)
                            );
                            // this.config.formData.areaIds = data.areaId;
                            // this.config.columns[0].multiple = false;
                            this.addNew = false;
                            this.showDialog = true;
                        },
                        filter: (data) => {
                            //data是当前选中数据;filter用于角色权限过滤
                            return true;
                        },
                    },
                    {
                        label: "删除",
                        class: "supcon-grid-link",
                        click: (row) => {
                            this.$confirm(
                                "此操作将删除该条记录, 是否继续?",
                                "提示",
                                {
                                    confirmButtonText: "确定",
                                    cancelButtonText: '取消',
                                    showCancelButton: true,
                                    closeOnClickModal:false,
                                    type: 'warning'
                                }
                            )
                                .then(() => {
                                    API.eventDeleteYellow({
                                        yellowId: row.id,
                                    }).then((res) => {
                                        this.$message.success("删除成功");
                                        this.onLoadList();
                                    });
                                })
                                .catch(() => {});
                        },
                    },
                ],
            };
        },
        getFormStartDates() {
            const self = this;
            return {
                prop: "startTime",
                label: "开始时间",
                is: "date",
                type: "datetime",
                notClearable: true,
                rules: [
                    {
                        required: true,
                    },
                ],
                valueFormat: "yyyy-MM-dd HH:mm:ss",
                callback: (data) => {
                    self.startTime = new Date(data).getTime();
                    // if (self.$refs.form.form.endTime) {
                    //     self.$refs.form.form.endTime = null;
                    // }
                },
            };
        },
        getFormEndDates() {
            return {
                prop: "endTime",
                label: "结束时间",
                is: "date",
                type: "datetime",
                notClearable: true,
                valueFormat: "yyyy-MM-dd HH:mm:ss",
                rules: [
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            if (value === "" || value === null) {
                                callback();
                            } else if (
                                this.startTime &&
                                new Date(value).getTime() <= this.startTime
                            ) {
                                callback(new Error("结束时间必须大于开始时间"));
                            } else {
                                callback();
                            }
                        },

                        trigger: ["blur", "change"],
                    },
                ],
                pickerOptions: {
                    disabledDate: (time) => {
                        return this.startTime
                            ? time.getTime() < this.startTime - 3600 * 12 * 1000
                            : false;
                    },
                },
            };
        },
        /**
         * 新建
         */
        onAdd() {
            // this.config.columns[0].multiple = true;
            // this.config.columns[0].hidden = true;
            this.config.formData = {
                startTime: formatDate(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
                endTime: `${new Date().getFullYear()}-12-31 23:59:59`,
            };
            this.addNew = true;
            this.showDialog = true;
            // setTimeout(() => {
            //     this.config.columns[0].hidden = false;
            //     this.showDialog = true;
            // }, 100);
        },
        onSync() {
            this.loading = this.$loading({
                lock: true,
                text: "同步中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
            API.eventSyncYellow()
                .then((res) => {
                    this.loading.close();
                    this.$message.success("同步成功");
                    this.onLoadList();
                })
                .catch((err) => {
                    this.loading.close();
                });
        },
        onCancel() {
            this.showDialog = false;
        },
        handleSubmit() {
            this.$refs.form.submit((form) => {
                let formData = { ...form };
                // if (this.addNew) {
                //     const codes = form.areaIds.join(",");
                //     formData = JSON.parse(JSON.stringify(form));
                //     formData.areaIds = codes;
                // } else {
                //     formData.areaId = form.areaIds;
                // }
                this.submitLoading = true;
                API.eventNewYellow(formData)
                    .then((res) => {
                        this.showDialog = false;
                        this.$message.success(this.addNew ? "添加成功" : "修改成功");
                        this.onLoadList();
                        this.submitLoading = false;
                    })
                    .catch((error) => {
                        this.submitLoading = false;
                    });
            });
        },
        onExport() {
            window.open(window.g.event_url + "/limit/yellow/export");
        },
        onUpload() {
            this.progressFlag = false;
            this.fileList = [];
            this.showDialogUpload = true;
        },
        onUploadSuccess(response, file, fileList) {
            this.progressUpload = 100;
            clearInterval(this.timer);
            if (response.code === 100) {
                this.fileList = [];
                this.onLoadList();
                this.$message.success("上传成功");
                this.showDialogUpload = false;
            }
        },
        onUploadError(err, file, fileList) {
            this.$message.error("上传失败");
        },
        onBeforeUpload(file) {
            let excelist = ["xls", "xlsx"];
            let flieArr = file.name.split(".");
            let fileSuffix = flieArr[flieArr.length - 1];
            let result = excelist.some(function (item) {
                return item == fileSuffix;
            });
            let flag = file.size < 1024 * 1024 * 10 && result;
            if (!flag) {
                this.$message.error("只能上传xls/xlsx文件，且不超过10M");
            } else {
                this.progressFlag = true;
                this.progressUpload = 0;
                this.timer = setInterval(() => {
                    if (this.progressUpload < 98) {
                        this.progressUpload++;
                    }
                }, 200);
            }

            return flag;
        },
        getCookie(name) {
            var strcookie = document.cookie;
            var arrcookie = strcookie.split("; ");
            for (var i = 0; i < arrcookie.length; i++) {
                var arr = arrcookie[i].split("=");
                if (arr[0] === name) {
                    return arr[1];
                }
            }
            return "";
        },
    },
};
</script>
<style>
</style>
